﻿using App.Desk.Extend;
using App.Model;
using App.Untiys;
using DtRlDeviceApiNet.Models;
using Newtonsoft.Json;
using SqlSugar;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Win.Dal;

namespace App.Desk.Pro.SamplingData
{
    public partial class FrmPlansList : UIPage
    {
        public int CurrentLocalBatch = -1;
        int CurrentRowIndex = -1;
        private QueryPageModel queryModel;
        public QueryPageModel QueryModel
        {
            get
            {
                if (queryModel == null)
                {
                    queryModel = new QueryPageModel();
                }
                return queryModel;
            }

            set
            {
                queryModel = value;
            }
        }

        public FrmPlansList()
        {
            InitializeComponent();
            InitGridViewColumns();
            InitQuery();
        }

        /// <summary>
        /// 初始化GridView
        /// </summary>
        public void InitGridViewColumns()
        {
            dataGridView.AutoGenerateColumns = false;
            dataGridView.ReadOnly = true;
            dataGridView.MultiSelect = false;
            dataGridView.RowHeadersVisible = false;
            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            var columns = Config.ModelToDataGridColumns<ProSampling>(new ProSampling());
            dataGridView.Columns.Clear();
            for (int i = 0; i < columns.Count; i++)
                if (columns[i].Name == "SetBucketNo")
                    if (Config.CurrentUser.IsAdmin == 1)
                        columns[i].Visible = true;
                    else
                        columns[i].Visible = false;
            dataGridView.Columns.AddRange(columns.ToArray());
        }

        /// <summary>
        /// 线程安全调用
        /// </summary>
        public void ThreadQuery()
        {
            var data = ProSamplingServices.GetList(CurrentLocalBatch);
            UIHelper.DoBindDataGrid(dataGridView, data);
        }

        public void InitQuery()
        {
            GetList();
        }

        public void GetList()
        {
            var data = ProSamplingServices.GetList(CurrentLocalBatch);
            dataGridView.DataSource = data;
        }

        private void dataGridView_SelectIndexChange(object sender, int index)
        {
            CurrentRowIndex = index;
        }

        private void FrmSamplingData_Load(object sender, EventArgs e)
        {
            queryModel = new QueryPageModel();
            CurrentLocalBatch = ProSamplingServices.GetMaxLocalBatch();
            btnAbandon.Visible = Config.CurrentUser.Abandon == 1;
            GetList();
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FrmAdd frmAdd = new FrmAdd();
            frmAdd.ShowDialog();
            CurrentLocalBatch = ProSamplingServices.GetMaxLocalBatch();
            GetList();
        }

        private void btnRef_Click(object sender, EventArgs e)
        {
        }

        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var samplingId = dataGridView.Rows[e.RowIndex].Cells["SamplingId"].Value.ToStringEx();
            var supplierCode = dataGridView.Rows[e.RowIndex].Cells["SupplierCode"].Value.ToStringEx();
            var isUpload = dataGridView.Rows[e.RowIndex].Cells["IsUpload"].Value.ToStringEx();
            if (isUpload == "测试")
            {
                FrmEditSupplierCode frmSupplier = new FrmEditSupplierCode(samplingId.ToIntEx(), supplierCode);
                frmSupplier.ShowDialog();
                GetList();
            }
        }

        /// <summary>
        /// 获取计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDown_Click(object sender, EventArgs e)
        {
            var result = DataTranf.GetHTML(Config.SdxLocalServerGetStatus);
            if (result != "服务正常")
            {
                UIMessageBox.ShowError(result);
                return;
            }
            LogHelper.DoWriteLogType(LogType.Plan, result);
            if (!UIMessageBox.ShowAsk("是否去三大项获取最新批次？"))
                return;
            btnDown.Enabled = false;
            try
            {
                LogHelper.DoWriteLogType(LogType.Plan, "开始获取计划");
                result = DataTranf.GetHTML(Config.SdxLocalServerGetPlans);
                LogHelper.DoWriteLogType(LogType.Plan, $"Result:{result}");
                if (!string.IsNullOrEmpty(result))
                {
                    int start = result.IndexOf('[');
                    int end = result.IndexOf(']');
                    result = result.Substring(start, end + 1);
                }
                if (result.Contains("Error"))
                {
                    UIMessageBox.ShowError(result);
                    LogHelper.DoWriteLogType(LogType.Plan, $"错误信息:{result}");
                    btnDown.Enabled = true;
                    return;
                }
                var trainInfos = JsonConvert.DeserializeObject<List<TrainInfo>>(result);
                if (trainInfos == null)
                    LogHelper.DoWriteLogType(LogType.Plan, $"trainInfos=null");
                List<ProSampling> samplings = new List<ProSampling>();
                var newLocalBatch = ProSamplingServices.GetNewLocalBatch();
                if (newLocalBatch <= 0)
                {
                    UIMessageBox.ShowError("生成本地批次异常");
                    btnDown.Enabled = true;
                    return;
                }
                LogHelper.DoWriteLogType(LogType.Plan, $"最新批次:{newLocalBatch}");
                if (trainInfos != null)
                    if (trainInfos.Count > 0)
                    {
                        trainInfos.ForEach(res =>
                        {
                            samplings.Add(new ProSampling
                            {
                                LocalBatch = newLocalBatch,
                                ActualSimplingLocation = "",//实际采样坐标，
                                SamplingPerson = Config.CurrentUser.ChName,
                                BatchInfoId = res.BatchInfoId.ToString(),
                                CanSampling = res.CanSampling,
                                CarNo = res.CarNo,
                                CarType = res.CarType,
                                CreateTime = res.CreateTime.GetValueOrDefault(),
                                IsSuccess = "待采",
                                IsUpload = "待传",
                                IsWeight = res.IsWeight.ToIntEx(),
                                OrgId = res.OrgId.ToString(),
                                SamplingEndTime = null,
                                SamplingId = 0,
                                SamplingStartTime = null,
                                SdxId = res.Id.ToString(),
                                SetBucketNo = res.SetBucketNo,
                                SimplingCode = res.SimplingCode,
                                SimplingLocation = res.SimplingLocation,
                                SimplingPic = "",
                                SimplingPoint = res.SimplingPoint.ToIntEx(),
                                SimplingSource = res.SimplingSource,
                                SimplingWeight = res.SimplingWeight.ToStringEx(),
                                Stretchposition = res.Stretchposition,
                                SupplierCode = res.SupplierCode,
                                SysId = res.SysId,
                                TrainIndex = res.TrainIndex.ToIntEx(),
                                TrainSamplingCode = res.TrainSamplingCode,
                                TransLong = res.TransLong,
                                TransWide = res.TransWide,
                                TravelNo = res.TravelNo,
                                VirtuallySimplingLocation = "",
                                IsTest = ""
                            });
                        });
                        ProSamplingServices.Add(samplings);
                        CurrentLocalBatch = ProSamplingServices.GetMaxLocalBatch();
                        GetList();
                        btnDown.Enabled = true;
                    }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError(ex.Message);
                btnDown.Enabled = true;
            }
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if ((CurrentLocalBatch - 1) <= 0)
            {
                UIMessageBox.ShowWarning("没有批次了");
                return;
            }
            CurrentLocalBatch = CurrentLocalBatch - 1;
            GetList();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (CurrentLocalBatch >= ProSamplingServices.GetMaxLocalBatch())
            {
                UIMessageBox.ShowWarning("已经是最新的批次");
                return;
            }
            CurrentLocalBatch = CurrentLocalBatch + 1;
            GetList();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            CurrentLocalBatch = ProSamplingServices.GetMaxLocalBatch();
            GetList();
        }

        private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            var ColumnName = dataGridView.Columns[e.ColumnIndex].Name;
            if (ColumnName == "IsSuccess" && e.Value != null)
            {
                // 根据单元格的值设置颜色
                if (e.Value.ToString() == "完成")
                    e.CellStyle.ForeColor = Color.Blue;
                else
                if (e.Value.ToString() == "弃采")
                {
                    e.CellStyle.BackColor = Color.IndianRed;
                    e.CellStyle.SelectionBackColor = Color.IndianRed;
                    e.CellStyle.ForeColor = Color.White;
                    e.CellStyle.SelectionForeColor = Color.AntiqueWhite;
                }

                // 指定当前单元格使用自定义样式
                e.FormattingApplied = true;
            }
            if (ColumnName == "IsUpload" && e.Value != null)
            {
                // 根据单元格的值设置颜色
                if (e.Value.ToString() == "已传")
                    e.CellStyle.ForeColor = Color.Blue;
                e.FormattingApplied = true;
            }
        }

        private void btnAbandon_Click(object sender, EventArgs e)
        {
            if (Config.CurrentUser.Abandon != 1)
            {
                UIMessageBox.ShowWarning("您没有强制权限");
                return;
            }
            if (CurrentRowIndex < 0)
            {
                UIMessageBox.ShowWarning("请选择一行");
                return;
            }
            var trainIndex = dataGridView.Rows[CurrentRowIndex].Cells["TrainIndex"].Value.ToIntEx();
            if (!UIMessageBox.ShowAsk($"是否将第{trainIndex}节车厢设置为弃采？"))
                return;
            var samplingId = dataGridView.Rows[CurrentRowIndex].Cells["SamplingId"].Value.ToIntEx();
            var currentSamplingData = ProSamplingServices.Info(new ProSampling { SamplingId = samplingId });
            if (currentSamplingData.IsSuccess != "待采")
            {
                UIMessageBox.ShowSuccess("只能操作待采数据");
                return;
            }
            if (ProSamplingServices.Abandon(samplingId, Config.CurrentUser.ChName))
            {
                var message = GlobalSampling.Screenshot(currentSamplingData);
                if (message != "OK")
                    UIMessageBox.ShowSuccess(message);
                Config.DoUploadDataToSdx(samplingId);
                UIMessageBox.ShowSuccess("操作成功");
                GetList();
            }
            else
            {
                UIMessageBox.ShowError("操作失败");
            }
        }
    }
}
